package com.lzhl.buildjar.dao.update;

import com.lzhl.buildjar.dao.BaseDao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库更新管理
 * @author 李柱良(@柱子的日月)
 * @date 2014/6/18
 */
public class UpdateManager extends BaseDao {

    private class Version {
        int version;
        Class clzzz;

        private Version(int version, Class clzzz) {
            this.version = version;
            this.clzzz = clzzz;
        }
    }

    private List<Version> versions = new ArrayList<Version>();

    public UpdateManager() {
        versions.add(new Version(1, Update_1.class));
    }

    public void update() throws SQLException {
        int oldVersion = queryOldVersion();

        for(Version version : versions) {
            if(version.version > oldVersion) {
                try {
                    Updater updater = (Updater) version.clzzz.newInstance();
                    updater.setConnection(getConnection());
                    updater.update();
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }

        Version version = versions.get(versions.size()-1);
        updateVersion(version.version);

        getConnection().commit();
    }

    private int queryOldVersion() throws SQLException {
        if(isTableExists("T_Version")) {
            String sql = "SELECT FVersion from T_Version";
            PreparedStatement pstmt = null;
            ResultSet rs = null;
            try {
                pstmt = getConnection().prepareStatement(sql);
                rs = pstmt.executeQuery();
                if(rs.next()) {
                    return rs.getInt("FVersion");
                }
            }
            finally {
                close(pstmt, rs);
            }
        }

        return 0;
    }

    private void updateVersion(int newVersion) throws SQLException {
        String sql = "UPDATE T_Version set FVersion = ?";
        PreparedStatement pstmt = null;
        try {
            pstmt = getConnection().prepareStatement(sql);
            pstmt.setInt(1, newVersion);
            pstmt.executeUpdate();
        }
        finally {
            close(pstmt);
        }
    }

}
